﻿#include "YToolWidget.h"
#include <QApplication>
#include <QScreen>
#include <QTimer>

YToolWidget::YToolWidget(QWidget *parent) : QWidget(parent)
{
    desktopSize = qApp->primaryScreen()->size();
    setWindowFlags(Qt::ToolTip | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);

    QTimer *timer = new QTimer(this);
    timer->setTimerType(Qt::TimerType::VeryCoarseTimer);
    connect(timer, &QTimer::timeout, [this]{ timeout(); });
    timer->start(20);
}

void YToolWidget::set(const QRect &rect)
{
    int x = (rect.x() + width() > desktopSize.width() ? desktopSize.width() - width() : rect.x());
    int y = rect.bottom() + 5;
    if(y + height() > desktopSize.height()){
        int testY = rect.y() - 5 - height();
        if(testY >= 0) y = testY; else y = 0;
        toped = true;
    }else{
        toped = false;
    }
    move(x, y);

    if(isHidden()) show();
    raise();
}

void YToolWidget::set(const QPoint &pos, const QSize &size)
{
    if(size.isValid()){
        set(QRect(pos, size));
    }else{
        set(QRect(pos.x(), 0, 1, pos.y()));
    }
}

void YToolWidget::unset()
{
    if(!isHidden()) {
        hide();
    }
}

void YToolWidget::timeout()
{
    if(isVisible()) raise();
}
